

const koa = require('koa')
const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const jweAuth = require('koa-jwt')
//秘钥
const secret = "it's a secret jjk"

//跨域问题
const cors = require('koa2-cors')
const koaBody = require("koa-body");
const static = require('koa-static')



const db = require("./lib/db");
const { getDB } = require('./lib/db');

db.initDB();

const fs = require("fs");
const path = require("path");

//去除密码再返回 
const { resetData } = require('./lib/resetData.js')




const app = new koa()
app.keys = ['some secret']
app.use(static(__dirname + '/'))
app.use(
    koaBody({
        multipart: true
    })
);
//跨域
app.use(cors({
    origin: '*',
    allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS', 'PUT'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With', 'Content-Length']
}))



//测试接口
router.get('/test', async ctx => {
    ctx.body = 'ok'
})

//添加用户
router.post('/users',

    async ctx => {
        console.log(ctx.request.body);

        res = ctx.request.body
        const sql = `INSERT INTO userlist (username,password) VALUES  (?,?)`;
        const [rows] = await getDB().execute(sql, [res.username, res.password]);
        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = {
                message: "添加成功",
                state: 200

            }

        } else {
            ctx.body = {
                message: "添加失败",
                state: 201
            }
        }
    })


//登录
router.post("/login", async ctx => {
    const { body } = ctx.request

    const { username, password } = body

    console.log(username, 'username');
    const [row] = await getDB().execute(`SELECT * FROM userlist WHERE username=? limit 1`, [username])
    if (row.length) {
        console.log(row);
        if (row[0].password === password) {
            if (row[0].manager === '1') {

                console.log(username);
                ctx.body = {
                    message: "登录成功",
                    state: 200,
                    user: username,
                    //生成token，返回给客户端
                    token: jwt.sign({
                        data: username,
                        //设置过期时间，单位为秒
                        // exp:Math.floor(Date.now()/1000)+60*60
                    }, secret)

                }
            } else {

                ctx.body = {
                    message: "登录失败,您不是管理员",
                    state: 401,

                }

            }


        } else {
            ctx.body = {
                message: "登录失败,密码错误",
                state: 201,

            }
        }

    } else {

        ctx.body = {
            message: "登录失败,用户名不存在",
            state: 201,

        }
    }
})


router.get('/exercisesList/:query?',
    jweAuth({ secret }),
    async ctx => {
        //ctx.state可以获取到加签时的数据
        // console.log(ctx.state.user.data, 'username')


        const queryobj = JSON.parse(ctx.query.query)
        const start = (queryobj.pagenum - 1) * (queryobj.pagesize)

        console.log(start);
        if (queryobj.query) {
            var sql = `SELECT * FROM exercises `
            const res = await getDB().execute(sql)
            const total = res[0].length
            sql += " WHERE titleDes LIKE ? LIMIT ?,?";
            const [row] = await getDB().execute(sql, ["%" + queryobj.query + "%", String(start), String(queryobj.pagesize)])

            ctx.body = { data: row, total: total }
        } else {
            var sql = `SELECT * FROM exercises `
            const res = await getDB().execute(sql)
            const total2 = res[0].length
            sql += " LIMIT ?,?";
            const [row] = await getDB().execute(sql, [String(start), String(queryobj.pagesize)])
            ctx.body = { data: row, total: total2 }
        }
    })




router.post('/exercisesList',
    jweAuth({ secret }),
    async ctx => {
        console.log(ctx.request.body);

        const res = ctx.request.body
        const sql = `INSERT INTO exercises (cateName,titleDes,answerA,answerB,answerC,answerRight,answerDes,source,level) VALUES  (?,?,?,?,?,?,?,?,?)`;
        const [rows] = await getDB().execute(sql, [res.cateName, res.titleDes, res.answerA, res.answerB, res.answerC, res.answerRight, res.answerDes, res.source, res.level]);
        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = {
                message: "添加成功",
                state: 200

            }



        } else {
            ctx.body = {
                message: "添加失败",
                state: 201
            }
        }
    })




router.delete('/exercisesList/:id',
    jweAuth({ secret }),
    async ctx => {
        const sql = `DELETE FROM exercises WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.params.id]);
        console.log(rows);
        ctx.body = {
            state: 200,
            message: '删除成功'
        }
    })

router.get('/exercises/:id',
    jweAuth({ secret }),
    async ctx => {
        console.log(ctx.params.id);
        const sql = `SELECT * FROM exercises WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.params.id]);

        ctx.body = { data: rows }
    })
//修改题目
router.put('/exercisesList/:id',
    jweAuth({ secret }),
    async ctx => {
        const res = ctx.request.body.editForm
        console.log(res.cateName, res.titleDes, res.answerA, res.answerB, res.answerC, res.answerRight, res.answerDes, res.source, res.level, ctx.params.id);


        const sql = `UPDATE exercises SET cateName=?,titleDes=?,answerA=?,answerB=?,answerC=?,answerRight=?,answerDes=?,source=?,level=? WHERE id=?`
        const [rows] = await getDB().execute(sql, [res.cateName, res.titleDes, res.answerA, res.answerB, res.answerC, res.answerRight, res.answerDes, res.source, res.level, ctx.params.id]);
        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = { data: "修改成功", state: 200 }
        } else {
            ctx.body = { data: "修改失败", state: 201 }
        }
    })

router.get('/complaint',
    jweAuth({ secret }),
    async ctx => {



        const queryobj = JSON.parse(ctx.query.query)
        const start = (queryobj.pagenum - 1) * (queryobj.pagesize)

        console.log(start);

        var sql = `SELECT * FROM complaintList `
        const res = await getDB().execute(sql)
        const total = res[0].length

        var sql1 = sql += " LIMIT ?,?";
        const [row] = await getDB().execute(sql1, [String(start), String(queryobj.pagesize)])
        ctx.body = { data: row, total: total }

    })

router.delete('/complaint/:id',
    jweAuth({ secret }),
    async ctx => {
        const sql = `DELETE FROM complaintList WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.params.id]);
        console.log(rows);
        ctx.body = {
            state: 200,
            message: '删除成功'
        }
    })



app.use(router.routes())
app.listen(8083, () => { console.log('serve built') })